package cn.itbeien.manager.service.impl;

import cn.itbeien.core.util.SnowFlake;
import cn.itbeien.manager.dao.merchant.QrCodeMerchantMapper;
import cn.itbeien.entity.MerchantInfo;
import cn.itbeien.entity.QrCodeMerchant;
import cn.itbeien.manager.service.IMerchantService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author beien
 * @date 2024-03-12 14:38
 * Copyright© 2024 beien
 * 商户业务服务类
 * 1.批量创建二维码
 * 2.根据二维码中的链接获取code，然后再根据code进行业务判断
 *
 */
@Service
public class MerchantService implements IMerchantService {

    private static SnowFlake snowFlake = new SnowFlake(1,1,1);

    @Resource
    private QrCodeMerchantMapper qrCodeMerchantMapper;


    /**
     * 根据二维码code进行业务路由
     * 1.进入小程序
     * 2.跳转到H5支付界面
     * @param code
     * @return
     */
    @Override
    public String bussinessRouter(String code) {
        String result = null;
        QrCodeMerchant qrCodeMerchant =  qrCodeMerchantMapper.queryMerchantByCode(code);

        if(qrCodeMerchant == null){
            //跳转到小程序 http://www.qq.com?merchantCode=merchantNo&code=code
            //可以拿到code 拿不到商户编号
            //把code缓存到redis
            //生成商户编号
            String merchantNo = "mn"+snowFlake.nextId();

            result = "success";
        }else{
            result = "doPay";
        }
        return null;
    }

    /**
     * 小程序注册商户
     * @param merchant
     * @return
     */
    //添加事务，让注册商户，商户和二维码绑定在同一个事务中
    @Transactional
    @Override
    public int regMerchant(MerchantInfo merchantInfo) {
        Integer result = 1;//0为执行成功 1为执行失败
      try{
          //保存商户信息
         int number = qrCodeMerchantMapper.saveMerchant(merchantInfo);

          QrCodeMerchant  qrCodeMerchant = new QrCodeMerchant();
          //商户编号
          qrCodeMerchant.setMerchantCode(merchantInfo.getMerchantNo());
          qrCodeMerchant.setQrCode(merchantInfo.getCode());//二维码编号
          //商户注册成功后再用二维码绑定商户
        int codeNumber =  qrCodeMerchantMapper.saveMerchantQrCode(qrCodeMerchant);
        if(number>0 && codeNumber>0){
            result = 0;//成功
        }

      }catch(Exception e){
          result = 1;//失败
      }
        return result;
    }

    /**
     * 根据H5页面传入的二维码编号获取商户信息
     * @param code
     * @return QrCodeMerchant 二维码和商户中间表
     */
    @Override
    public QrCodeMerchant findMerchantByCode(String code)
    {
        QrCodeMerchant merchantInfo  = qrCodeMerchantMapper.queryMerchantByCode(code);
        return merchantInfo;
    }


}
